// This expects to be called on an element such as a div, td, etc. that will contain
// a child img tag. It is this img tag's src and alt attributes that will be rotated.
// Optionally, surround the img tag in an a tag to have its href rotated.
// The format of the images array should be 
// [{'src':'http://imgsrv.com/myimg.jpg','alt':'some caption or alt text','href':'http://somelink.com/link'}]
(function ($) {
    $.fn.imageRotator = function (options) {
        var settings = {
            'images': [],
            'rotationTimerMs': 3000
        };

        if (options) {
            $.extend(settings, options);
        }

        var _imageCount = 0;
        var _rotateTimer;
        var _currentIndex = -1;
        var _a;
        var _img;

        var images = settings.images;
        if (images && 0 < images.length) {

            _imageCount = images.length;
			
			findChildren(this);
			
			if (null != _img && 0 < _img.length)
			{
				rotateNext();

				this.mouseenter(stopRotateTimer);
				this.mouseleave(startRotateTimer);
				startRotateTimer();
			}
        }

        function findChildren(container) {
            _a = container.find('a.imageRotator');
            _img = container.find('img.imageRotator');
        }

        function rotateNext() {
            _currentIndex = _currentIndex + 1 == _imageCount ? 0 : _currentIndex + 1;
            refreshImageSource();
        }

        function refreshImageSource() {
			// This only gets called if _img was found during initialization
            _img.attr('src', settings.images[_currentIndex].src);
            _img.attr('alt', settings.images[_currentIndex].alt);
			
			// However, we don't require the <a> tag to be present
			if (null != _a) 
			{
				_a.attr('href', settings.images[_currentIndex].href);
			}
        }

        function startRotateTimer() {
            _rotateTimer = setInterval(onRotateTimer, settings.rotationTimerMs);
        }

        function stopRotateTimer() {
            clearInterval(_rotateTimer);
        }
		
		function onRotateTimer() {
            rotateNext();
        }
    };
})(jQuery);